package com.jt.auth.impl;

import com.jt.auth.service.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserDetailsService接口的实现类负责:
 * 1)通过查询内存获取用户信息(默认)
 * 2)通过数据库获取用户信息
 * 3)通过Feign接口调用远端Service获取用户信息(本次选择)
 * */
@Service
public class UserDatailsServiceImpl implements UserDetailsService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户名获取远端用户信息
        com.jt.auth.pojo.User user=remoteUserService.selectUserByUsername(username);
        if (user==null)throw new UsernameNotFoundException("user is not exits");
        //2.基于用户id获取远端用户权限信息
        List<String> permissions=remoteUserService.selectUserPermissions(user.getId());
        //3.封装结果并返回(交给认证对象-AuthenticationManager,完成用户身份认证)
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
    }
    //说明:这个方法我们只负责写,不负责调用,这个方法默认就在一个调用链.
}
